const { Sequelize, DataTypes } = require('sequelize');

// 实例化Sequelize，完成链接配置
const sequelize = new Sequelize('node', 'root', '123456', {
    host: 'localhost',
    dialect: 'mysql',
    dialectOptions: { charset: "utf8mb4" },
    define: {
        underscored: true,
        charset: 'utf8mb4',
        freezeTableName: true
    },
    pool: {
        max: 5,
        min: 0,
        idle: 10000
    }
});

const User = sequelize.define('User', {
    userId: {
        type: DataTypes.INTEGER,
        autoIncrement: true,
        primaryKey: true
    },
    username: {
        type: DataTypes.STRING,
        allowNull: false
    },
    password: {
        type: DataTypes.STRING,
        allowNull: false
    }
});

(async function() {
    try {
        // 做链接校验
        await sequelize.authenticate();
        console.log('连接成功');

        // 同步模型
        await User.sync({ force: true });
        console.log("用户模型表刚刚（重新)建立");

        // 创建一个User实例，插入表
        const jane = await User.create({ username: "Jane", password: "520" });
        console.log("Jane 创建成功:", jane.toJSON());
    } catch (error) {
        console.error('Unable to connect to the database:', error);
    }
})();
